package com.bkgrands.fpmu.activities;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.app.Dialog;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;

import com.android.tu.loadingdialog.LoadingDialog;
import com.bkgrands.fpmu.R;
import com.bkgrands.fpmu.Retro.APIClient;
import com.bkgrands.fpmu.Retro.APIInterface;
import com.bkgrands.fpmu.Retro.CommonMethod;
import com.bkgrands.fpmu.classes.CMResponse;
import com.bkgrands.fpmu.classes.Headmaster;
import com.bkgrands.fpmu.classes.StaticFarm;
import com.gitonway.lee.niftymodaldialogeffects.lib.Effectstype;
import com.gitonway.lee.niftymodaldialogeffects.lib.NiftyDialogBuilder;
import com.jeevandeshmukh.glidetoastlib.GlideToast;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LoginActivity extends AppCompatActivity {
    SharedPreferences loginPreferences;
    SharedPreferences.Editor loginPrefsEditor;
    ImageButton signin;
    EditText email, password;
    CheckBox checkBox;
    APIInterface apiInterface;
    String uname;
    String pwd;
    Dialog myDialog;
    Boolean saveLogin;
    NiftyDialogBuilder materialDesignAnimatedDialog;
    public static String headname, headsch, headdist;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        apiInterface = APIClient.getClient().create(APIInterface.class);
        signin = (ImageButton) findViewById(R.id.signin);
        email = (EditText) findViewById(R.id.email);
        password = (EditText) findViewById(R.id.password);
        checkBox = (CheckBox) findViewById(R.id.checkbox);
        loginPreferences = getSharedPreferences("loginPrefs", MODE_PRIVATE);
        loginPrefsEditor = loginPreferences.edit();
        materialDesignAnimatedDialog = NiftyDialogBuilder.getInstance(this);
        myDialog = new Dialog(this);


        saveLogin = loginPreferences.getBoolean("saveLogin", false);
        if (saveLogin == true) {
            email.setText(loginPreferences.getString("email", ""));
            password.setText(loginPreferences.getString("password", ""));
            checkBox.setChecked(true);
        }

        signin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String useremail = email.getText().toString();
                final String userpassword = password.getText().toString();
                if (checkBox.isChecked()) {
                    loginPrefsEditor.putBoolean("saveLogin", true);
                    loginPrefsEditor.putString("email", useremail);
                    loginPrefsEditor.putString("password", userpassword);
                    loginPrefsEditor.commit();
                } else {
                    loginPrefsEditor.clear();
                    loginPrefsEditor.commit();
                }
                if (checkValidation()) {
                    if (CommonMethod.isNetworkAvailable(LoginActivity.this))
                        loginRetrofit2Api();
                    else
                        CommonMethod.showAlert("Internet Connectivity Failure", LoginActivity.this);
                }
            }
        });

    }


    private void loginRetrofit2Api() {
        LoadingDialog.Builder builder1 = new LoadingDialog.Builder(LoginActivity.this)
                .setMessage("Logging...")
                .setCancelable(false);
        final LoadingDialog dialog1 = builder1.create();
        dialog1.show();

        String usermail = email.getText().toString();
        String userpword = password.getText().toString();
        StaticFarm.user_name=usermail;
        StaticFarm.user_password=userpword;
        Call<CMResponse> call1 = apiInterface.AuthUser(usermail,userpword);
        call1.enqueue(new Callback<CMResponse>() {
            @Override
            public void onResponse(Call<CMResponse> call, Response<CMResponse> response) {
                Log.d("GGG", response.body().toString());
                if (response.isSuccessful()) {
                    // get response
                    CMResponse loginResponse = response.body();

                    if(loginResponse.getIt().equals("worked")){
                        // success code
                        dialog1.dismiss();
                        onLoginSuccess();
                        new GlideToast.makeToast(LoginActivity.this, "Login Successful", GlideToast.LENGTHLONG, GlideToast.SUCCESSTOAST, GlideToast.BOTTOM).show();
                        // goo your MainActivity and getHeadName
                        StaticFarm.responseAtLogin = loginResponse;
                       headname=StaticFarm.responseAtLogin.getHeadmaster().getHeadName();
                       headsch=StaticFarm.responseAtLogin.getHeadmaster().getSchoolName();
                       headdist=StaticFarm.responseAtLogin.getHeadmaster().getDistrict();

                        final Handler handler = new Handler();
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
                                startActivity(intent);
                                overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                            }
                        }, 3000);
                    }
                    else if(loginResponse.getIt().equals("failed")){
                        // <<error code
                        dialog1.dismiss();
                        onLoginFailed();
                        new GlideToast.makeToast(LoginActivity.this, "Login Failed. Invalid Credentials", GlideToast.LENGTHLONG, GlideToast.FAILTOAST, GlideToast.BOTTOM).show();

                    }

                }
                else {
                    // When it doesnt work
                    int code = response.code();
                }
            }

            @Override
            public void onFailure(Call<CMResponse> call, Throwable t) {
                String msd = t.toString();
                dialog1.dismiss();
                onLoginFailed();

                new GlideToast.makeToast(LoginActivity.this, "Login Failed", GlideToast.LENGTHLONG, GlideToast.FAILTOAST, GlideToast.BOTTOM).show();
            }
        });

    }

    public boolean checkValidation() {
        uname = email.getText().toString();
        pwd = password.getText().toString();

        if (email.getText().toString().trim().equals("")) {
            CommonMethod.showAlert("School Code Cannot be left blank", LoginActivity.this);
            return false;
        } else if (password.getText().toString().trim().equals("")) {
            CommonMethod.showAlert("Password Cannot be left blank", LoginActivity.this);
            return false;
        }
        return true;
    }

    public void onLoginSuccess() {
        signin.setEnabled(true);
        myDialog.setContentView(R.layout.successpop);
        myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        myDialog.show();
        new android.os.Handler().postDelayed(
                new Runnable() {
                    public void run() {
                        myDialog.dismiss();
                    }
                }, 3000);
    }

    public void onLoginFailed() {
        myDialog.setContentView(R.layout.failpop);
        myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        myDialog.show();
        new android.os.Handler().postDelayed(
                new Runnable() {
                    public void run() {
                        myDialog.dismiss();
                    }
                }, 3000);
    }

    @Override
    public void onBackPressed() {
        animatedDialog1();
    }

    public void animatedDialog1() {
        materialDesignAnimatedDialog
                .withTitle("Exit")
                .withMessage("Are you sure you want to exit?.")
                .withDialogColor("#7535AD")
                .withButton1Text("OK")
                .withDuration(700)
                .withEffect(Effectstype.Fliph)
                .setButton1Click(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                })
                .show();
    }

}